package my.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtil {
	private static ThreadLocal<Connection> connList = new ThreadLocal<Connection>();
	static {
		try {
			Class.forName(JdbcProperties.driver);
		} catch (ClassNotFoundException e) {
		}
	}

	private JDBCUtil() {
	}

	/**
	 * 得到数据库连接
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		Connection conn = connList.get();
		if (conn == null) {
			try {
				conn = DriverManager.getConnection(JdbcProperties.url, JdbcProperties.username, JdbcProperties.password);
				conn.setAutoCommit(false);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			connList.set(conn);
		}
		return conn;
	}

	/**
	 * 关闭数据库连接
	 */
	public static void closeConnection() {
		Connection conn = connList.get();
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
			}
			connList.set(null);
		}
	}
}
